import { getToken, setToken, removeToken, setUsername, removeUsername, setPassword, removePassword, setRememberMe, removeRememberMe } from '@/utils/auth'
import { login } from '@/api/login/login'

// 村赤用户令牌和角色信息
const state ={
    token: getToken(),
    userInfo: JSON.parse(localStorage.getItem('userInfo')) || {},
    roles: [] //角色
}

const mutations ={
    SET_TOKEN: (state,token) => {
        state.token = token
    },
    SET_USERINFO: (state,userInfo) => {
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        state.userInfo = userInfo
    },
    SET_ROLES: (state,roles) => {
        state.roles = roles
    }
};

const actions = {
    // 用户登录
    login({ commit }, loginForm) {
        return new Promise((resolve,reject) => {
            setTimeout(() => {
                const params = {
                    userName: loginForm.username,
                    password: loginForm.password
                }
                login(params).then(res => {
                    if (res.status === 200) {
                        if (loginForm.rememberMe) {
                            setUsername(loginForm.username)
                            setPassword(loginForm.password)
                            setRememberMe(loginForm.rememberMe)
                        } else {
                            removeUsername()
                            removePassword()
                            removeRememberMe()
                        }

                        // 保存状态
                        commit('SET_TOKEN', res.data.token);
                        commit('SET_USERINFO', res.data);
                        
                        // 写入cookie
                        setToken(res.data.token)
                        resolve()
                    } else {
                        reject(res.msg)
                    }
                }).catch(error => {
                    reject(error)
                })
            },1000)
        })
    },
    // 获取用户角色信息
    getInfo({ commit, state }){
        return new Promise((resolve) => {
            setTimeout(() => {
                const roles = state.token === 'admin' ? ['admin'] : ['jerry']
                commit('SET_ROLES',roles)
                resolve({roles})
            },1000)
        })
    },
    // 重置令牌
    resetToken({ commit }){
        return new Promise(resolve => {
            commit('SET_TOKEN','')
            commit('SET_USERINFO',{})
            commit('SET_ROLES',[])
            removeToken()
            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}